<?php
declare(strict_types=1);
namespace App\Service\Goods\Cart;
use App\Models\Goods\CartItem;
class CartSave implements CartSaveInterface {
    public function add($request):bool{
        $user   = $request->user();
        $skuId  = $request->input('sku_id');
        $amount = $request->input('amount');
        // 从数据库中查询该商品是否已经在购物车中
        if ($cart = $user->cartItems()->where('product_sku_id', $skuId)->first()) {
            // 如果存在则直接叠加商品数量
            $cart->update([
                'amount' => $cart->amount + $amount,
            ]);
        } else {
            // 否则创建一个新的购物车记录
            $cart = new CartItem(['amount' => $amount]);
            $cart->user()->associate($user);
            $cart->productSku()->associate($skuId);
            $cart->save();
        }
        return true;
    }

}
